import json
from datetime import datetime

from django.core.paginator import Paginator
from django.http import JsonResponse
from django.views import View

from tree.models import TreeDW, TreeDWSerializer, Tree, TreeSerializer


# Create your views here.
# 查询所有数据
class ListView(View):
    def get(self, req):
        obj_list = TreeDW.objects.all().values()  # .values() 转成字典
        return JsonResponse({'code': 200, 'data': list(obj_list)})  # 把外层的容器转为List后返回


# 根据tree id获取信息
class GetTreeDW(View):
    def get(self, req):
        tree = Tree.objects.get(id=int(req.GET['tree_id']))
        obj = TreeDW.objects.filter(tree=tree)
        if len(obj) != 0:
            return JsonResponse({'code': 200, 'data': TreeDWSerializer(obj[0]).data})
        else:
            return JsonResponse({'code': 500, 'msg': '查询不到数据！'})


# 获取未录入鲜重的样木信息
class GetNoDWTree(View):
    def post(self, req):
        data = json.loads(req.body.decode('utf-8'))
        pageNum = data.get('pageNum', 1)  # 当前页，如果不存在则默认为1
        pageSize = data.get('pageSize', 10)  # 每页大小
        query = data.get('query', '')  # 查询参数

        obj_dw = TreeDW.objects.all()
        dw_tree_ids = [obj.tree.id for obj in obj_dw]
        # print(dw_tree_ids)
        obj_NoDWTree = Tree.objects.exclude(id__in=dw_tree_ids)

        # 分页
        paginator = Paginator(obj_NoDWTree, pageSize)
        dataPage = paginator.page(pageNum)

        # print(len(obj_NoDWTree), TreeSerializer(obj_NoDWTree, many=True).data)
        return JsonResponse({'code': 200, 'total': len(obj_NoDWTree),
                             'data': TreeSerializer(dataPage, many=True).data})  # 把外层的容器转为List后返回


# 信息查询
class SearchView(View):
    def post(self, req):
        data = json.loads(req.body.decode('utf-8'))
        pageNum = data['pageNum']  # 当前页
        pageSize = data['pageSize']  # 每页大小
        query = data['query']  # 查询参数

        # 获取查询集
        queryset = TreeDW.objects.filter(id__icontains=query)
        total = queryset.count()

        # 分页
        paginator = Paginator(queryset, pageSize)
        dataPage = paginator.page(pageNum)

        # 序列化数据 - 传递查询集给序列化器
        serializer = TreeDWSerializer(dataPage.object_list, many=True)

        # dataPage = Paginator(Tree.objects.filter(number__icontains=query), pageSize).page(pageNum)
        # # data = list(dataPage.object_list.values())  # 先转成字典，再转成列表
        # total = Tree.objects.filter(number__icontains=query).count()

        return JsonResponse({'code': 200, 'data': serializer.data, 'total': total})


class ActionView(View):
    # 根据id获取信息
    def get(self, req):
        try:
            obj = TreeDW.objects.get(id=req.GET.get('id'))
            return JsonResponse({'code': 200, 'data': TreeDWSerializer(obj).data})
        except TreeDW.DoesNotExist:
            return JsonResponse({'code': 404, 'msg': '数据不存在'})
        except Exception as e:
            return JsonResponse({'code': 500, 'msg': f'系统错误: {str(e)}'})

    def delete(self, request):
        """
        删除操作
        :param request:
        :return:
        """
        idList = json.loads(request.body.decode("utf-8"))
        TreeDW.objects.filter(id__in=idList).delete()
        return JsonResponse({'code': 200})


# 新增或修改
class SaveView(View):
    def post(self, request):
        data = json.loads(request.body.decode('utf-8'))
        tree = Tree.objects.get(id=data['tree'])
        if data['id'] == -1:  # 添加
            obj = TreeDW(
                tree=tree, barkT=data['barkT'], barkC=data['barkC'], barkB=data['barkB'],
                trunkT=data['trunkT'], trunkC=data['trunkC'], trunkB=data['trunkB'],
                branchT=data['branchT'], branchC=data['branchC'], branchB=data['branchB'],
                leafT=data['leafT'], leafC=data['leafC'], leafB=data['leafB'],
                rhizome=data['rhizome'], root_large=data['root_large'], root_fine=data['root_fine'],
                remark=data['remark'])
            obj.create_time = datetime.now().date()
            obj.save()
        else:  # 修改
            obj = TreeDW(id=data['id'], tree=tree,
                         barkT=data['barkT'], barkC=data['barkC'], barkB=data['barkB'],
                         trunkT=data['trunkT'], trunkC=data['trunkC'], trunkB=data['trunkB'],
                         branchT=data['branchT'], branchC=data['branchC'], branchB=data['branchB'],
                         leafT=data['leafT'], leafC=data['leafC'], leafB=data['leafB'],
                         rhizome=data['rhizome'], root_large=data['root_large'], root_fine=data['root_fine'],
                         remark=data['remark'])
            obj.update_time = datetime.now().date()
            obj.save()
        return JsonResponse({'code': 200, 'msg': '执行成功！'})
